package API;

import Util.MyKey;
import Util.Tools;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 退款异步通知处理类
 * 文档地址：https://open.heepay.com/www/index.html#/openDoc?type=menu&id=2022230232
 */
public class HyRefund_notify {

    // 定义需要参与签名的参数名，确保与文档一致
    private static final String[] SIGN_PARAMS = {
            "agent_id", "hy_bill_no", "agent_bill_id",
            "agent_refund_bill_no", "refund_amt",
            "refund_status", "hy_deal_time"
    };

    /**
     * 处理退款异步通知并验证签名
     * @param notifyStr 通知字符串（包含参数部分）
     * @return 验证结果
     * @throws UnsupportedEncodingException 编码异常
     */
    public boolean processNotify(String notifyStr) throws UnsupportedEncodingException {
        // 解析通知参数
        Map<String, String> params = Tools.getURLParameters(notifyStr);
        if (params.isEmpty()) {
            System.out.println("通知参数解析失败");
            return false;
        }

        // 提取签名并验证参数完整性
        String receivedSign = params.get("sign");
        if (receivedSign == null || receivedSign.isEmpty()) {
            System.out.println("未包含签名参数");
            return false;
        }

        // 构建待签名字符串
        StringBuilder signBuilder = new StringBuilder();
        for (String paramName : SIGN_PARAMS) {
            String value = params.getOrDefault(paramName, "");
            signBuilder.append(paramName).append("=").append(value).append("&");

            // 打印关键参数信息
            if ("refund_amt".equals(paramName)) {
                System.out.println("退款金额：" + value);
            } else if ("refund_status".equals(paramName)) {
                System.out.println("退款状态：" + value);
            }
        }

        // 追加密钥并转为小写
        signBuilder.append("key=").append(MyKey.RefundMD5Key);
        String signSource = signBuilder.toString().toLowerCase();
        System.out.println("\n根据通知内容组装的待签名串：" + signSource);

        // 计算并验证签名
        String calculatedSign = Tools.getMD5(signSource);
        boolean verifyResult = calculatedSign.equals(receivedSign);

        System.out.println(verifyResult ? "验签验证成功" : "验签验证失败");
        return verifyResult;
    }

    public static void main(String[] args) {
        try {
            // 测试用例：异步通知参数
            String notifyParams = "http://www.baidu.com/notify?agent_id=1664502&hy_bill_no=H2509151812174A5&agent_bill_id=BSP20250915000002002&agent_refund_bill_no=BSR20250915000000001&refund_amt=0.01&refund_status=SUCCESS&hy_deal_time=20250915145949&sign=4914ae471c6d52a44a148e6fb6fe10bc";

            HyRefund_notify notifyProcessor = new HyRefund_notify();
            notifyProcessor.processNotify(notifyParams);
        } catch (UnsupportedEncodingException e) {
            System.err.println("处理通知时发生编码错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("处理通知时发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
